/* components */
import { RoleViewContentStayAllotViewHeader, RoleViewUserTable, RoleViewAllotRoleModal, RoleViewDefaultAllotModal } from '@src/modules/account/role/component'
import NoDataViewNew from '@src/component/common/NoDataViewNew'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
/* hooks */
import { 
  useStoreFetchRoleAllotRoles, 
  useStoreFetchRoleAutoAuthSave, 
  useStoreFetchRoleTree, 
  useStoreFetchUserList, 
  useStoreTableSelection, 
  useStoreUserPage 
} from "@src/modules/account/role/store/hooks"
import useLoading from '@src/modules/account/role/hooks/useLoading'
import useShbStorage from '@src/modules/account/role/hooks/useShbStorage'
import { useRoleViewAuth, useRoleViewFetchAutoAuth, useRoleViewTableMatchSelected, useRoleViewTenantBuyAndUseUserNum } from '@src/modules/account/role/hooks'
/* model */
import Role from '@model/entity/Role/Role'
import { RoleUserListModel } from '@model/param/in/Role'
import { RoleViewUserTableVM } from '@src/modules/account/role/component/RoleViewUserTable'
import LoginUser from '@model/entity/LoginUser/LoginUser'
import { RoleViewAllotRoleModalVM } from '@src/modules/account/role/component/RoleViewAllotRoleModal'
import { RoleViewDefaultAllotModalVM } from '@src/modules/account/role/component/RoleViewDefaultAllotModal'
import MsgModel from '@model/MsgModel'
import { 
  DEFAULT_ROLE_ALLOT_AUTO_SAVE_ERROR_MESSAGE, 
  DEFAULT_ROLE_ALLOT_AUTO_SAVE_SUCCESS_MESSAGE, 
  ROLE_ALLOT_SUCCESS_MESSAGE 
} from '@src/model/const/Alert'
import { RoleViewUserTablePageStorageData, RoleViewUserTablePageStorageKey } from '@src/modules/account/role/model'
/* scss */
import '@src/modules/account/role/component/RoleViewContentStayAllotView/index.scss'
/* vue */
import { ComponentInstance, computed, ComputedRef, defineComponent, onBeforeMount, reactive, Ref, ref, toRefs } from 'vue'
/* util */
import { isEmpty, isFalse } from '@src/util/type'
import { strConcat as concat } from 'pub-bbx-utils'
import { message } from '@src/util/message'
import { loadingPromise } from '@src/modules/account/role/util'
/* service */
import RoleService from '@service/RoleService'
import { RoleIdEnum } from '@model/enum/RoleEnum'
import {t as $t} from '@src/locales';

export type RoleViewContentStayAllotViewProps = {

}

export interface RoleViewContentStayAllotViewSetupState {
  currentSelectRole: ComputedRef<Role>;
}

export enum RoleViewContentStayAllotViewEventEnum {
  Input = 'input'
}

export type RoleViewContentStayAllotViewEmitsOptions = {
  input: () => void;
}

export type RoleViewContentStayAllotViewInstance = ComponentInstance & RoleViewContentStayAllotViewSetupState
export type RoleViewContentStayAllotViewVM = RoleViewContentStayAllotViewSetupState & RoleViewContentStayAllotViewProps & ComponentInstance


export default defineComponent({
  name: ComponentNameEnum.RoleViewContentStayAllotView,
  emits: [RoleViewContentStayAllotViewEventEnum.Input],
  components: {
    [NoDataViewNew.name]: NoDataViewNew
  },
  setup(props: RoleViewContentStayAllotViewProps, { slots, emit }) {
    
    const fetchUserList = useStoreFetchUserList()
    const { userPage, userList, isUserListEmpty } = useStoreUserPage()
    const { tableSelection, setTableSelection } = useStoreTableSelection()
    const { loading } = useLoading()
    
    const fetchRoleAllotRoles = useStoreFetchRoleAllotRoles()
    const fetchRoleTree = useStoreFetchRoleTree()
    const fetchRoleAutoAuthSave = useStoreFetchRoleAutoAuthSave()
    const tableMatchSelected = useRoleViewTableMatchSelected()
    const { fetchRoleTenantBuyAndUseUserNumImpl } = useRoleViewTenantBuyAndUseUserNum()
    const fetchAutoAuth = useRoleViewFetchAutoAuth()
    
    const { canDefaultAllotUser } = useRoleViewAuth()
    
    const tablePageData = useShbStorage<RoleViewUserTablePageStorageData>(RoleViewUserTablePageStorageKey, { user: 10 })
    
    const RoleViewUserContentTableComponent: Ref<RoleViewUserTableVM | null> = ref(null)
    const RoleViewAllotRoleModalComponent: Ref<RoleViewAllotRoleModalVM | null> = ref(null)
    const RoleViewDefaultAllotModalComponent: Ref<RoleViewDefaultAllotModalVM | null> = ref(null)
    
    let currentTableAllotRoleUser: LoginUser | Record<string, any> = {}
    
    let defaultAutoAuthRoleId: Ref<string> = ref('')
    
    let params: RoleUserListModel = reactive({
      enabled: '',
      keyword: '',
      pageNum:  1,
      pageSize: tablePageData.value.user,
      roleId: '',
      roleType: 'noauth'
    })
    
    const total: ComputedRef<number> = computed(() => {
      return userPage.value.total
    })
    
    function fetchUserListHandler(params: RoleUserListModel) {
      fetchUserList(params).then(() => {
        
        // @ts-ignore
        const tableComponent = RoleViewUserContentTableComponent.value?.$refs.BizTableComponent?.$refs?.TableComponent
        
        tableMatchSelected(tableComponent)
        
      })
    }
    
    function initFetchUserList() {
      
      params.pageNum = 1
      params.roleId = ''
      
      clearSelectionHandler()
      
      fetchUserList(params)
    }
    
    function handlerKeywordInput(keyword: string) {
      params.keyword = keyword
    }
    
    function handlerKeywordChange() {
      clearSelectionHandler()
      fetchUserListHandler(params)
    }
    
    function onPaginationPageNumChangedHandler(pageNum: number) {
      
      params.pageNum = pageNum
      
      fetchUserListHandler(params)
    }
    
    function onPaginationPageSizeChangedHandler(pageSize: number) {
      
      params.pageSize = pageSize
      tablePageData.value.user = pageSize
      
      fetchUserListHandler(params)
      
    }
    
    function onChangeSelectionHandler(selection: LoginUser[]) {
      setTableSelection(selection)
    }
    
    function clearSelectionHandler() {
      onChangeSelectionHandler([])
      RoleViewUserContentTableComponent.value && RoleViewUserContentTableComponent.value.clearSelection()
    }
    
    function onBatchAllotButtonClickHandler() {
      
      if (isEmpty(tableSelection.value)) {
        message.error($t('account.selectMemberAllotRole'))
        return
      }
      
      currentTableAllotRoleUser = {}
      
      openRoleViewAllotRoleModal()
    }
    
    function onAllotButtonClickHandler(user: LoginUser) {
      currentTableAllotRoleUser = user
      openRoleViewAllotRoleModal()
    }
    
    function openRoleViewAllotRoleModal() {
      RoleViewAllotRoleModalComponent.value && RoleViewAllotRoleModalComponent.value.outsideShow()
    }
    
    function openRoleViewDefaultAllotModal() {
      RoleViewDefaultAllotModalComponent.value && RoleViewDefaultAllotModalComponent.value.outsideShow()
    }
    
    function hideRoleViewAllotRoleModal() {
      RoleViewAllotRoleModalComponent.value && RoleViewAllotRoleModalComponent.value.outsideHide()
    }
    
    function hideRoleViewDefaultAllotModal() {
      RoleViewDefaultAllotModalComponent.value && RoleViewDefaultAllotModalComponent.value.outsideHide()
    }
    
    async function onAllotModalSubmitHandler(roleIdList: string[]) {
      
      await loadingPromise(loading.value)
      
      // 是否为单个分配角色
      const isSingleAllot = isEmpty(currentTableAllotRoleUser)
      // 当前选中的用户id列表
      const userIds = isSingleAllot ? tableSelection.value.map(user => user.userId) : [currentTableAllotRoleUser.userId]
      
      const params = {
        roleIdList: concat(roleIdList),
        userIdList: concat(userIds)
      }
      
      fetchRoleAllotRoles(params).then(result => {
        
        const isFail = MsgModel.isFail(result)
        
        if (isFail) {
          message.error(result.message)
          return
        }
        
        message.success(ROLE_ALLOT_SUCCESS_MESSAGE)
        
        hideRoleViewAllotRoleModal()
        
        initFetchUserList()
        
        fetchRoleTree()
        
        fetchRoleTenantBuyAndUseUserNumImpl()
        
      })
      
    }
    
    async function onDefaultAllotModalSubmitHandler(roleId: string) {
      
      await loadingPromise(loading.value)
      
      // 是否为系统管理员手动指定
      const isAdminAssign = roleId == RoleIdEnum.AdminAssign
      
      const params = {
        state: !isAdminAssign,
        roleId
      }
      
      fetchRoleAutoAuthSave(params).then(result => {
        
        const isFail = MsgModel.isFail(result)
        
        if (isFail) {
          message.error(DEFAULT_ROLE_ALLOT_AUTO_SAVE_ERROR_MESSAGE)
          return
        }
        
        message.success(DEFAULT_ROLE_ALLOT_AUTO_SAVE_SUCCESS_MESSAGE)
        
        hideRoleViewDefaultAllotModal()
        
      })
      
    }
    
    function onDefaultAllotButtonClickHandler() {
      openRoleViewDefaultAllotModal()
    }
    
    function fetchAutoAuthImpl() {
      
      if (isFalse(canDefaultAllotUser.value)) return
      
      fetchAutoAuth().then(result => {
        const id = result?.id || ''
        defaultAutoAuthRoleId.value = id
      })
    }
    
    onBeforeMount(() => {
      initFetchUserList()
      fetchAutoAuthImpl()
    })
    
    return {
      params: toRefs(params),
      loading,
      total,
      userList,
      isUserListEmpty,
      RoleViewUserContentTableComponent,
      RoleViewAllotRoleModalComponent,
      RoleViewDefaultAllotModalComponent,
      defaultAutoAuthRoleId,
      handlerKeywordInput,
      handlerKeywordChange,
      onPaginationPageNumChangedHandler,
      onPaginationPageSizeChangedHandler,
      onChangeSelectionHandler,
      clearSelectionHandler,
      openRoleViewAllotRoleModal,
      onAllotModalSubmitHandler,
      onAllotButtonClickHandler,
      onBatchAllotButtonClickHandler,
      openRoleViewDefaultAllotModal,
      onDefaultAllotButtonClickHandler,
      onDefaultAllotModalSubmitHandler
    }
    
  },
  render() {
    return (
      <div class={ComponentNameEnum.RoleViewContentStayAllotView}>
        
        <div class="role-view-content-stay-allot-view__title">
          {this.$t('common.base.unallotMember')}
        </div>
        
        <RoleViewContentStayAllotViewHeader 
          keyword={this.params.keyword.value}
          onInput={this.handlerKeywordInput}
          onChange={this.handlerKeywordChange}
          onAllot={this.onBatchAllotButtonClickHandler}
          onDefault={this.onDefaultAllotButtonClickHandler}
        />
          
        <RoleViewUserTable 
          ref='RoleViewUserContentTableComponent'
          is-allot
          data={this.userList}
          total={this.total}
          pageSize={this.params.pageSize.value}
          pageNum={this.params.pageNum.value}
          onChangePageNum={this.onPaginationPageNumChangedHandler}
          onChangePageSize={this.onPaginationPageSizeChangedHandler}
          onSelect={this.onChangeSelectionHandler}
          onAllot={this.onAllotButtonClickHandler}
          isEmpty={this.isUserListEmpty}
        />
        
        <RoleViewAllotRoleModal 
          ref="RoleViewAllotRoleModalComponent" 
          onSubmit={this.onAllotModalSubmitHandler}
        />
        
        <RoleViewDefaultAllotModal 
          ref="RoleViewDefaultAllotModalComponent" 
          defaultAutoAuthRoleId={this.defaultAutoAuthRoleId}
          onSubmit={this.onDefaultAllotModalSubmitHandler}
        />
        
      </div>
    ) as any
  }
}) as any
